#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    File Name:      opencv_utils
    Author:         'daze'
    date:           2018/12/12
"""
import os
import cv2
import numpy as np

from AutoWool.main.config.config_utils import ConfigUtils
from AutoWool.main.utils.log_utils import Log


class OpencvUtils:

    # src_img_abs_path 是待检测的源图像绝对路径，template_img_name 是 _img 目录中模板图片的名称
    # 返回 tuple，包含 x,y,w,h
    @staticmethod
    def get_template_img_loc_w_h(src_img_abs_path, template_img_name):
        Log.log(
            '开始执行 OpencvUtils get_template_img_loc_w_h() 方法,src_img_abs_path=' + src_img_abs_path + ' template_img_name=' + template_img_name)
        img_rgb = cv2.imread(src_img_abs_path)
        img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
        template_img_abs_path = os.path.join(ConfigUtils.Dir.get_img_dir_abs_path(), template_img_name)
        template = cv2.imread(template_img_abs_path, 0)
        template_w, template_h = template.shape[::-1]  # 得到图像的宽高
        w_h_tuple = (template_w, template_h)
        # 开始匹配模板图像并得到其 location
        res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
        threshold = 0.7  # 大于 0.5 竟然找不到了你敢信？
        loc = np.where(res >= threshold)
        real_location_tuple = ()
        for pt in zip(*loc[::-1]):
            real_location_tuple = pt
            # cv2.rectangle(img_rgb, pt, (pt[0] + template_w, pt[1] + template_h), (0, 255, 255), 2)
        # cv2.imshow('Detected', img_rgb)
        # input()
        if real_location_tuple == ():
            Log.log('OpencvUtils real_location_tuple == ()')
            return ()
        Log.log('get_template_img_loc_w_h 方法：real_location_tuple=' + str(real_location_tuple) + ' w_h_tuple=' + str(
            w_h_tuple))
        return real_location_tuple + w_h_tuple

    # 标记图像的指定位置
    @staticmethod
    def sign_target_img(src_img_abs_path, *point):
        # 使用该方法在窗口中显示图片并标记各个 point，但是窗口什么东西也没有，点击会停止响应
        # img_rgb = cv2.imread(src_img_abs_path)
        # cv2.imshow('image', img_rgb)
        pass
